﻿using System;
using System.Collections.Generic;
using UnityEngine;

public class TimeTaskComponent:MonoSingleton<TimeTaskComponent>
{
    long instanceID=0;
    static Dictionary<long, Data> pairs = new Dictionary<long, Data>();
    public static long AddTask(float time, Action action)
    {
        Inst.instanceID++;
        var data = new Data
        {
            startTime = Time.realtimeSinceStartup,
            endTime = time,
            action = action
        };
        pairs.Add(Inst.instanceID, data);
        return Inst.instanceID;
    }

    public static float GetTime(long key)
    {
        if (!pairs.ContainsKey(key))
            return 0;

        return pairs[key].totalTime;
    }

    public void Remove(long key)
    {
        if (!pairs.ContainsKey(key))
            return;

        pairs.Remove(key);
    }

    private void Update()
    {
        reset:
        foreach (var key in pairs.Keys)
        {
            var item = pairs[key];
            item.totalTime = (Time.realtimeSinceStartup - item.startTime);
            if (item.totalTime>=item.endTime)
            {
                item.action();
                pairs.Remove(key);
                goto reset;
            }
        }
    }

    public class Data
    {
        public float startTime;
        public float endTime;
        public float totalTime=0;
        public Action action;
    }
}